<?php 
define('SITE_ROOT','http://localhost:90/ihelp');
require_once (ROOT . DS . 'library' . DS . 'phptal' . DS . 'PHPTAL.php');

session_start(); 
if(isset($_POST)){
	if(isset($_POST["productId"])){
		$productId = $_POST["productId"];
	}
	if(isset($_POST["amountAvailable"])){
		$amountAvailable = $_POST["amountAvailable"];
	}
	if(isset($_POST["amountDesired"])){
		$amountDesired = $_POST["amountDesired"];
	}
}

if (!isset($_POST['submit'])) { // if page is not submitted to itself echo the form
	$template = new PHPTAL(VIEW_TEMPLATE_FOLDER . DS . 'StockActions' . DS . 'insertForm.html');

	$template->cssRootFolderUrl = SITE_ROOT . DS . "css" . DS;
	$template->imgRootFolderUrl = SITE_ROOT . DS . "img" . DS;
	
	$template->formAction = curPageURL();
	$message = getucceedMessage();
	$template->succeedMessageExists = succeedMessageExists($message);
	$template->succeedMessage = $message;
	$template->action = $action;
	
	// execute the template
	try {
		echo $template->execute();
	}
	catch (Exception $e){
		echo $e;
	}
}
else{
	$action->insert($productId, $amountAvailable, $amountDesired);
	$productName = $action->getProductName($productId);
	$_SESSION["message"] = "Inserted: "." ". $productName . " ( aantal beschikbaar: " . $amountAvailable . ", aantal gewenst: ". $amountDesired . " ) ";
	header("Location: " . "http://localhost:90/iHelp/productManager.php");
}

//################################### METHODS ############################################

function succeedMessageExists($message){
	if($message != ''){
		return true;
	}
	return false;
}

function getucceedMessage(){
	$returnMessage = null;
	if(isset($_SESSION["message"])){
		$returnMessage =& $_SESSION["message"];
		unset($_SESSION["message"]);
	}
	return $returnMessage;
}

function curPageURL() {
	$pageURL = 'http';
	if (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
		$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	return $pageURL;
}
?>